<template>
	<el-container class="friend-page im-container">
		<el-aside :width="asideWidth + 'px'" class="aside">
			<div class="header">
				<el-input class="search-text" size="small" placeholder="搜索好友" v-model="searchText">
					<template #prefix>
						<i class="fas fa-search"></i>
					</template>
				</el-input>
				<el-button plain class="add-btn" title="添加好友" @click="onShowAddFriend()">
					<i class="fas fa-user-plus"></i>
				</el-button>
				<add-friend :dialogVisible="showAddFriend" @close="onCloseAddFriend"></add-friend>
			</div>
			<el-scrollbar class="friend-items" v-if="friendStore.friends && friendStore.friends.length > 0">
				<div v-for="(friends, i) in friendValues" :key="i">
					<div class="letter">{{ friendKeys[i] }}</div>
					<div v-for="(friend) in friends" :key="friend.id">
						<friend-item :friend="friend" :active="friend.id === activeFriend.id"
							@chat="onSendMessage(friend)" @delete="onDelFriend(friend)" @info="onActiveItem(friend)"
							@click.native="onActiveItem(friend)">
						</friend-item>
					</div>
					<div v-if="i < friendValues.length - 1" class="divider"></div>
				</div>
			</el-scrollbar>

			<!-- 空状态 -->
			<div v-else class="empty-friend-list">
				<div class="empty-content">
					<i class="fas fa-user-friends empty-icon"></i>
					<h3 class="empty-title">暂无好友</h3>
					<p class="empty-desc">添加好友开始聊天，建立更多有趣的连接</p>
					<div class="empty-actions">
						<el-button type="primary" @click="onShowAddFriend" class="action-btn">
							<i class="fas fa-user-plus"></i>
							添加好友
						</el-button>
					</div>
				</div>
			</div>

			<!-- 水平拉伸分隔器 -->
			<resizable-divider direction="horizontal" :min-width="200" :max-width="400" @resize="handleAsideResize" />
		</el-aside>
		<el-container class="container">
			<div class="header" v-show="userInfo.id">
				{{ userInfo.nickName }}
			</div>
			<div v-show="userInfo.id" class="container-box">
				<div class="friend-info">
					<div>
						<head-image :size="160" :name="userInfo.nickName" :url="userInfo.headImage" radius="10%"
							@click.native="showFullImage()"></head-image>
						<el-button class="send-btn" type="primary" v-show="isFriend"
							@click="onSendMessage(activeFriend)">
							<i class="fas fa-comment-dots"></i> 发消息
						</el-button>
					</div>
					<div>
						<div class="info-item">
							<el-descriptions title="好友信息" class="description" :column="1">
								<el-descriptions-item label="用户名">{{ userInfo.userName }}
								</el-descriptions-item>
								<el-descriptions-item label="昵称">{{ userInfo.nickName }}
								</el-descriptions-item>
								<el-descriptions-item label="性别">{{
									userInfo.sex === 1 ? "男" :
										userInfo.sex === 0 ? "女" : "未知"
								}}</el-descriptions-item>
								<el-descriptions-item label="签名">{{ userInfo.signature }}</el-descriptions-item>
							</el-descriptions>
						</div>
						<div class="btn-group">
							<el-button v-show="!isFriend" type="primary" @click="onAddFriend(userInfo)">
								<i class="fas fa-user-plus"></i> 加为好友
							</el-button>
							<el-button v-show="isFriend" type="danger" @click="onDelFriend(userInfo)">
								<i class="fas fa-user-times"></i> 删除好友
							</el-button>
						</div>
					</div>
				</div>
			</div>
			<div v-show="!userInfo.id" class="content-empty-state">
				<i class="welcome-icon fas fa-user-friends"></i>
				<h3 class="welcome-title">选择一个好友查看详情</h3>
				<p class="welcome-desc">从左侧选择一个好友，查看详细信息并开始聊天</p>
			</div>
		</el-container>
	</el-container>
</template>

<script>
import FriendItem from "@/components/IMFriend/FriendItem.vue";
import AddFriend from "@/components/IMFriend/AddFriend.vue";
import HeadImage from "@/components/common/HeadImage.vue";
import ResizableDivider from "@/components/common/ResizableDivider.vue";
import { pinyin } from 'pinyin-pro';
import { delFriendApi, addFriendApi } from '@/api/imFriend.js';
import { findUserByIdApi } from '@/api/imUser.js';
import { getAsideWidth, saveAsideWidth, debounce } from "@/utils/im/layoutPreferences.js";

export default {
	name: "IMFriend",
	components: {
		FriendItem,
		AddFriend,
		HeadImage,
		ResizableDivider
	},
	data() {
		return {
			searchText: "",
			showAddFriend: false,
			userInfo: {},
			activeFriend: {},
			asideWidth: getAsideWidth('friend') // 侧边栏宽度，从本地存储恢复
		}
	},
	methods: {
		// 处理侧边栏拉伸
		handleAsideResize(size) {
			if (size.width) {
				this.asideWidth = size.width;
				// 防抖保存到本地存储
				this.debouncedSaveAsideWidth(size.width);
			}
		},
		onShowAddFriend() {
			this.showAddFriend = true;
		},
		onCloseAddFriend() {
			this.showAddFriend = false;
		},
		onActiveItem(friend) {
			this.activeFriend = friend;
			this.loadUserInfo(friend.id);
		},
		onDelFriend(friend) {
			this.$confirm(`确认删除'${friend.nickName}',并清空聊天记录吗?`, '确认解除?', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				delFriendApi(friend.id).then(() => {
					this.$message.success("删除好友成功");
					this.friendStore.removeFriend(friend.id);
					this.chatStore.removePrivateChat(friend.id);
				}).catch((error) => {
					this.$message.error("删除好友失败：" + (error.message || "未知错误"));
				})
			})
		},
		onAddFriend(user) {
			addFriendApi(user.id).then(() => {
				this.$message.success("添加成功，对方已成为您的好友");
				let friend = {
					id: user.id,
					nickName: user.nickName,
					headImage: user.headImage,
					online: user.online
				}
				this.friendStore.addFriend(friend);
			}).catch((error) => {
				this.$message.error("添加好友失败：" + (error.message || "未知错误"));
			})
		},
		/**
		 * 点击发消息按钮，跳转到聊天界面
		 * 注意：这里不更新会话时间，保持最近聊天记录的时间
		 */
		onSendMessage(friend) {
			let chat = {
				type: 'PRIVATE',
				targetId: friend.id,
				showName: friend.nickName,
				headImage: friend.headImage,
				isDnd: friend.isDnd
			};
			// 第二个参数为false，表示不更新会话时间
			this.chatStore.openChat(chat, false);
			this.chatStore.setActiveChat(0);
			this.$router.push("/im/chat");
		},
		showFullImage() {
			if (this.userInfo.headImage) {
				this.$eventBus.$emit("openFullImage", this.userInfo.headImage);
			}
		},
		updateFriendInfo() {
			if (this.isFriend) {
				// store的数据不能直接修改，深拷贝一份store的数据
				let friend = JSON.parse(JSON.stringify(this.activeFriend));
				friend.headImage = this.userInfo.headImageThumb;
				friend.nickName = this.userInfo.nickName;
				this.chatStore.updateChatFromFriend(friend);
				this.friendStore.updateFriend(friend);
			}
		},
		loadUserInfo(id) {
			// 获取好友用户信息
			findUserByIdApi(id).then((res) => {
				this.userInfo = res.data;
				this.updateFriendInfo();
			}).catch((error) => {
				console.error("获取用户信息失败：", error);
			})
		},
		firstLetter(strText) {
			// 使用pinyin-pro库将中文转换为拼音
			let pinyinOptions = {
				toneType: 'none', // 无声调
				type: 'normal' // 普通拼音
			};
			let pyText = pinyin(strText, pinyinOptions);
			return pyText[0];
		},
		isEnglish(character) {
			return /^[A-Za-z]+$/.test(character);
		}
	},
	computed: {
		isFriend() {
			return this.friendStore.isFriend(this.userInfo.id);
		},
		friendMap() {
			// 按首字母分组
			let map = new Map();
			this.friendStore.friends.forEach((f) => {
				if (f.deleted || (this.searchText && !f.nickName.includes(this.searchText))) {
					return;
				}
				let letter = this.firstLetter(f.nickName).toUpperCase();
				// 非英文一律为#组
				if (!this.isEnglish(letter)) {
					letter = "#"
				}
				if (f.online) {
					letter = '在线'
				}
				if (map.has(letter)) {
					map.get(letter).push(f);
				} else {
					map.set(letter, [f]);
				}
			})
			// 排序
			let arrayObj = Array.from(map);
			arrayObj.sort((a, b) => {
				// #组在最后面
				if (a[0] == '#' || b[0] == '#') {
					return b[0].localeCompare(a[0])
				}
				return a[0].localeCompare(b[0])
			})
			map = new Map(arrayObj.map(i => [i[0], i[1]]));
			return map;
		},
		friendKeys() {
			return Array.from(this.friendMap.keys());
		},
		friendValues() {
			return Array.from(this.friendMap.values());
		}
	},
	mounted() {
		// 初始化防抖保存函数
		this.debouncedSaveAsideWidth = debounce((width) => {
			saveAsideWidth('friend', width);
		}, 300);
	}
}
</script>

<style lang="scss" scoped>
@use "@/styles/variables.scss" as *;

.friend-page {
	height: 100%;
	width: 100%;
	overflow: hidden; // 隐藏所有滚动条，防止页面出现左右滑动条
	box-sizing: border-box; // 确保边框和内边距不会导致溢出

	.aside {
		display: flex;
		flex-direction: column;
		background: var(--im-bg-secondary);
		border-right: var(--im-border);
		height: 100%;
		position: relative;

		.header {
			height: 60px;
			display: flex;
			align-items: center;
			padding: var(--im-spacing-lg);
			border-bottom: var(--im-border);
			background: var(--im-bg-primary);
			position: relative;

			// 添加微妙的阴影
			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 0;
				right: 0;
				height: 1px;
				background: linear-gradient(90deg, transparent, var(--im-border-color-light), transparent);
			}

			.search-text {
				flex: 1;
				margin-right: var(--im-spacing-sm);

				:deep(.el-input__wrapper) {
					border-radius: var(--im-border-radius-lg);
					border: var(--im-border);
					background: var(--im-bg-tertiary);
					transition: all var(--im-transition-base);

					&:hover {
						border-color: var(--im-color-primary);
					}

					&.is-focus {
						border-color: var(--im-color-primary);
						box-shadow: 0 0 0 2px rgba(var(--im-color-primary-rgb), 0.1);
					}
				}

				:deep(.el-input__prefix) {
					color: var(--im-text-color-secondary);
					display: flex;
					align-items: center;
					justify-content: center;
					height: 100%;
				}

				:deep(.el-input__inner) {
					color: var(--im-text-color-primary);
					background: transparent;

					&::placeholder {
						color: var(--im-text-color-placeholder);
					}
				}
			}

			.add-btn {
				padding: var(--im-spacing-sm) !important;
				margin-left: var(--im-spacing-sm);
				font-size: 16px;
				border-radius: var(--im-border-radius-round);
				border: var(--im-border);
				background: var(--im-bg-primary);
				color: var(--im-text-color-secondary);
				transition: all var(--im-transition-base);

				&:hover {
					background: var(--im-color-primary);
					color: white;
					border-color: var(--im-color-primary);
					transform: translateY(-1px);
				}
			}
		}

		.friend-items {
			flex: 1;
			background: var(--im-bg-primary);
			padding: var(--im-spacing-xs) 0;

			// 隐藏水平滚动条
			:deep(.el-scrollbar__wrap) {
				overflow-x: hidden !important;
				padding-right: 4px; // 为滚动条留出空间
			}

			:deep(.el-scrollbar__bar.is-horizontal) {
				display: none !important;
			}

			.letter {
				text-align: left;
				font-size: var(--im-font-size-lg);
				font-weight: var(--im-font-weight-semibold);
				padding: 5px 15px;
				color: var(--im-text-color-secondary);
				background: var(--im-bg-secondary);
				margin: var(--im-spacing-xs) 0;
				border-radius: var(--im-border-radius-base);
			}

			// 好友列表容器
			>div {
				position: relative;

				// 为每个好友项添加分隔效果（除了字母分组标题）
				>div:not(.letter):not(:last-child) {
					position: relative;

					&::after {
						content: '';
						position: absolute;
						bottom: 0;
						left: var(--im-spacing-xl);
						right: var(--im-spacing-xl);
						height: 1px;
						background: var(--im-border-color-light);
						opacity: 0.3;
					}
				}
			}
		}

		// 空状态样式
		.empty-friend-list {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;
			background: var(--im-bg-primary);

			.empty-content {
				text-align: center;
				max-width: 300px;
				padding: var(--im-spacing-xl);

				.empty-icon {
					font-size: 64px;
					color: var(--im-color-primary);
					margin-bottom: var(--im-spacing-lg);
					opacity: 0.6;
					animation: pulse 2s infinite;
				}

				.empty-title {
					color: var(--im-text-color-primary);
					font-size: var(--im-font-size-lg);
					font-weight: 600;
					margin: 0 0 var(--im-spacing-sm) 0;
				}

				.empty-desc {
					color: var(--im-text-color-secondary);
					font-size: var(--im-font-size-base);
					margin: 0 0 var(--im-spacing-xl) 0;
					line-height: 1.5;
				}

				.empty-actions {
					.action-btn {
						border-radius: var(--im-border-radius-base);
						padding: var(--im-spacing-sm) var(--im-spacing-lg);
						font-size: var(--im-font-size-sm);
						transition: all var(--im-transition-base);

						&:hover {
							transform: translateY(-1px);
							box-shadow: var(--im-box-shadow-hover);
						}

						i {
							margin-right: var(--im-spacing-xs);
						}
					}
				}
			}
		}
	}

	.container {
		display: flex;
		flex-direction: column;
		background: var(--im-bg-primary);
		min-width: 0; // 防止flex子元素溢出
		flex: 1; // 占据剩余空间

		.header {
			height: 60px; // 与左侧搜索框区域高度对齐
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 0 12px;
			line-height: 60px;
			font-size: var(--im-font-size-larger);
			font-weight: var(--im-font-weight-semibold);
			color: var(--im-text-color-primary);
			background: var(--im-bg-primary);
			border-bottom: var(--im-border);
			box-sizing: border-box;
		}

		// 容器盒子 - 参照群组页面实现
		.container-box {
			overflow: auto;
			padding: 20px;
			flex: 1;
			background: var(--im-bg-primary);
		}

		// 好友详细信息容器 - 参照群组页面样式实现，支持深色模式
		.friend-info {
			display: flex;
			padding: 20px;
			background: var(--im-bg-primary); // 使用主题背景色，自动适配深色模式

			// 头像区域
			>div:first-child {
				display: flex;
				flex-direction: column;
				align-items: center;
				margin-right: 40px;

				// 发消息按钮样式 - 参照群组页面
				.send-btn {
					margin-top: var(--im-spacing-lg);
					padding: var(--im-spacing-sm) var(--im-spacing-lg);
					border-radius: var(--im-border-radius-base);
					font-size: var(--im-font-size-base);
					font-weight: var(--im-font-weight-medium);
					transition: all var(--im-transition-base);

					&:hover {
						transform: translateY(-1px);
						box-shadow: var(--im-box-shadow-hover);
					}

					&:active {
						transform: translateY(0);
					}

					i {
						margin-right: var(--im-spacing-xs);
					}
				}
			}

			// 信息区域
			>div:last-child {
				flex: 1;
				max-width: 700px;
			}

			.info-item {
				// 使用IM主题变量，支持深色模式自动切换
				background: var(--im-bg-primary);
				border-radius: var(--im-border-radius-lg);
				transition: all var(--im-transition-base);

				// 深色模式下Element Plus描述列表组件样式适配
				// 确保所有背景色和文字色都正确应用主题变量
				:deep(.el-descriptions) {
					background: var(--im-bg-primary);

					// 标题样式
					.el-descriptions__title {
						color: var(--im-text-color-primary);
						font-weight: var(--im-font-weight-semibold);
						font-size: var(--im-font-size-lg);
					}

					// 标签样式（如"用户名"、"昵称"等）
					.el-descriptions__label {
						color: var(--im-text-color-secondary);
						background: var(--im-bg-primary);
					}

					// 内容样式（具体的值）
					.el-descriptions__content {
						color: var(--im-text-color-primary);
						background: var(--im-bg-primary);
					}

					// 表格相关元素的背景色适配
					.el-descriptions__body {
						background: var(--im-bg-primary);
					}

					.el-descriptions__table {
						background: var(--im-bg-primary);
					}

					tr {
						background: var(--im-bg-primary);
					}

					td {
						background: var(--im-bg-primary);
						border-color: var(--im-border-color);
					}
				}
			}

			.description {
				padding: 0;
			}
		}

		.btn-group {
			text-align: left !important;
			padding: 20px;

			.el-button {
				margin-right: var(--im-spacing-base);
				border-radius: var(--im-border-radius-base);
				transition: all var(--im-transition-base);

				&:hover {
					transform: translateY(-1px);
					box-shadow: var(--im-box-shadow-hover);
				}

				&:active {
					transform: translateY(0);
				}

				i {
					margin-right: var(--im-spacing-xs);
				}
			}
		}

		.content-empty-state {
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: var(--im-spacing-xl);
			background: var(--im-bg-primary);
			text-align: center;

			.welcome-icon {
				font-size: 64px;
				color: var(--im-color-primary);
				margin-bottom: var(--im-spacing-lg);
				opacity: 0.8;
			}

			.welcome-title {
				color: var(--im-text-color-primary);
				font-size: var(--im-font-size-lg);
				font-weight: 600;
				margin: 0 0 var(--im-spacing-base) 0;
			}

			.welcome-desc {
				color: var(--im-text-color-secondary);
				font-size: var(--im-font-size-base);
				margin: 0;
				line-height: 1.5;
			}
		}
	}
}
</style>